import {
  Entity,
  PrimaryGeneratedColumn,
  Column,
  CreateDateColumn,
  UpdateDateColumn,
  ManyToOne,
  JoinColumn,
} from 'typeorm';
import { ApiProperty } from '@nestjs/swagger';
import { Match } from './match.entity';

/**
 * 投注赔率实体
 */
@Entity({ name: 'bettings', comment: '投注赔率表' })
export class Betting {
  @ApiProperty({ description: '投注ID' })
  @PrimaryGeneratedColumn({ comment: '投注ID' })
  id: number;

  @ApiProperty({ description: '比赛ID' })
  @Column({ 
    name: 'match_id',
    comment: '关联比赛ID' 
  })
  matchId: number;

  @ApiProperty({ description: '竞彩编号' })
  @Column({ 
    name: 'jingcai_number',
    length: 50,
    nullable: true,
    comment: '竞彩编号' 
  })
  jingcaiNumber: string;

  @ApiProperty({ description: '北单编号' })
  @Column({ 
    name: 'beidan_number',
    length: 50,
    nullable: true,
    comment: '北单编号' 
  })
  beidanNumber: string;

  @ApiProperty({ description: '竞彩单关' })
  @Column({ 
    name: 'jingcai_single',
    length: 50,
    nullable: true,
    comment: '竞彩单关' 
  })
  jingcaiSingle: string;

  @ApiProperty({ description: '竞彩让球' })
  @Column({ 
    name: 'jingcai_handicap',
    type: 'decimal',
    precision: 5,
    scale: 2,
    nullable: true,
    comment: '竞彩让球数' 
  })
  jingcaiHandicap: number;

  @ApiProperty({ description: '北单让球' })
  @Column({ 
    name: 'beidan_handicap',
    type: 'decimal',
    precision: 5,
    scale: 2,
    nullable: true,
    comment: '北单让球数' 
  })
  beidanHandicap: number;

  @ApiProperty({ description: '胜赔率' })
  @Column({ 
    name: 'win_odds',
    type: 'decimal',
    precision: 8,
    scale: 2,
    nullable: true,
    comment: '胜赔率' 
  })
  winOdds: number;

  @ApiProperty({ description: '平赔率' })
  @Column({ 
    name: 'draw_odds',
    type: 'decimal',
    precision: 8,
    scale: 2,
    nullable: true,
    comment: '平赔率' 
  })
  drawOdds: number;

  @ApiProperty({ description: '负赔率' })
  @Column({ 
    name: 'lose_odds',
    type: 'decimal',
    precision: 8,
    scale: 2,
    nullable: true,
    comment: '负赔率' 
  })
  loseOdds: number;

  @ApiProperty({ 
    description: '推荐结果',
    example: ["win", "draw"],
    type: [String]
  })
  @Column({ 
    name: 'recommended_result',
    type: 'text',  
    nullable: true,
    comment: '推荐结果数组，可选值：win,draw,lose',
    transformer: {
      to: (value: string[]) => {
        console.log('转换到数据库的值:', value);
        return value ? JSON.stringify(value) : null;
      },
      from: (value: string) => {
        console.log('从数据库读取的值:', value);
        if (!value) return null;
        
        try {
          // 如果已经是数组，直接返回
          if (Array.isArray(value)) {
            return value;
          }
          
          // 尝试解析 JSON 字符串
          if (typeof value === 'string') {
            // 处理类似 ['win'] 这样的字符串格式
            if (value.startsWith('[') && value.endsWith(']')) {
              // 移除方括号并按逗号分割
              const cleanValue = value.slice(1, -1).trim();
              if (cleanValue === '') return [];
              
              // 分割并清理每个元素
              return cleanValue.split(',').map(item => 
                item.trim().replace(/^['"]|['"]$/g, '')
              );
            }
            
            // 尝试标准 JSON 解析
            return JSON.parse(value);
          }
          
          return null;
        } catch (e) {
          console.error('JSON解析错误:', e, '原始值:', value);
          // 如果解析失败，尝试作为单个值处理
          if (typeof value === 'string' && value.trim()) {
            return [value.trim().replace(/^['"]|['"]$/g, '')];
          }
          return null;
        }
      }
    }
  })
  recommendedResult: string[];

  @ApiProperty({ description: '主队比分' })
  @Column({ 
    name: 'home_score',
    type: 'int',
    nullable: true,
    comment: '主队比分' 
  })
  homeScore: number;

  @ApiProperty({ description: '客队比分' })
  @Column({ 
    name: 'away_score',
    type: 'int',
    nullable: true,
    comment: '客队比分' 
  })
  awayScore: number;

  @ApiProperty({ 
    description: '比赛结果',
    example: 'win',
    enum: ['win', 'draw', 'lose']
  })
  @Column({ 
    name: 'match_result',
    length: 10,
    nullable: true,
    comment: '比赛结果：win-主胜，draw-平局，lose-主负' 
  })
  matchResult: string;

  @ApiProperty({ description: '预测是否命中' })
  @Column({ 
    name: 'prediction_hit',
    type: 'boolean',
    nullable: true,
    comment: '预测是否命中' 
  })
  predictionHit: boolean;

  @ApiProperty({ description: '创建时间' })
  @CreateDateColumn({ 
    name: 'created_at',
    comment: '创建时间' 
  })
  createdAt: Date;

  @ApiProperty({ description: '更新时间' })
  @UpdateDateColumn({ 
    name: 'updated_at',
    comment: '更新时间' 
  })
  updatedAt: Date;

  @ApiProperty({ description: '关联比赛', type: () => Match })
  @ManyToOne(() => Match, match => match.bettings)
  @JoinColumn({ name: 'match_id' })
  match: Match;
}